package com.tuijian.service.recommend;

import com.tuijian.service.filter.FilterService;
import com.tuijian.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RecommendService {

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private FilterService filterService;

    @Resource
    private ThreadPoolTaskExecutor executor;

    @Value("${server.pageSize}")
    private int pageSize;

    private String key;
    int start=0;

    public List<String> getList(String userId, String type){
        List<String> list = new ArrayList<>();
        if (redisUtils.keys("*").contains("post"+userId)||redisUtils.keys("*").contains("prod"+userId)){
            key = type.equals("0")? "post"+userId : "prod"+userId;
            list = redisUtils.popReader(key,pageSize);
        }else {
            key = type.equals("0")? "top_card" : "top_prod";
            start = redisUtils.keys("*").contains(key+userId) ? redisUtils.getCacheObject(key+userId):0;
            start = start>40 ? 0:start;
            list = redisUtils.pageReader(key, start, pageSize);
            redisUtils.setCacheObject(key+userId, start+pageSize);
        }

        if (redisUtils.size(key)<10 || start>10){
            executor.execute(()->startRecommend(userId,type));
        }
        System.out.println(list);
        return list;
    }


    public void startRecommend(String userId, String type){
        System.out.println("================");
        System.out.println("开始过滤");
        filterService.filterMethod(userId,type);
        System.out.println("排序完成");
//        try {
//            for(int i=0;i<10;i++){
//                System.out.println(executor.getThreadNamePrefix()+i);
//                Thread.sleep(1000);
//            }
//
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
    }

}
